package com.talkyoung.ptbpro.controller;

import com.github.pagehelper.PageHelper;
import com.talkyoung.ptbcommon.CommonResult;
import com.talkyoung.ptbpojo.entity.*;
import com.talkyoung.ptbpro.common.util.IdGenerateUtil;
import com.talkyoung.ptbpro.common.util.SecurityUserUtil;
import com.talkyoung.ptbpro.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.sql.Blob;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


@RestController
@RequestMapping("/blobArticle")
public class BlobArticleController {

    private static final Logger logger = LoggerFactory.getLogger(BlobArticleController.class);

    @Autowired
    UserService userService;

    @Autowired
    BlobArticleService blobArticleService;

    @Autowired
    PictureService pictureService;

    @Autowired
    SlideShowService slideShowService;

    @Autowired
    UserArticleThumbUpService userArticleThumbUpService;

    @Autowired
    UserStatisticsService userStatisticsService;
    /**
     * 获取Home article
     * @return
     */
    @PreAuthorize("hasRole('R_EDIT_BLOG_Q')")
    @RequestMapping(value = "/selectToHome", method = RequestMethod.GET)
    public CommonResult<List<BlobArticleWithBLOBs>> selectOrderByTime(@RequestParam Integer userId) {
        PageHelper.startPage(1,100);
        BlobArticleExample blobArticleExample = new BlobArticleExample();
        BlobArticleExample.Criteria criteria = blobArticleExample.createCriteria();
        criteria.andIsPublicEqualTo(1);
        blobArticleExample.setOrderByClause("create_time desc");
        List<BlobArticleWithBLOBs> blobArticles = blobArticleService.selectByExampleWithBLOBs(blobArticleExample);
        UserArticleThumbUpKey userArticleThumbUpKey = new UserArticleThumbUpKey();
        userArticleThumbUpKey.setUserId(userId);
        for(BlobArticle blobArticle:blobArticles){
            userArticleThumbUpKey.setArticleId(blobArticle.getId());
            UserArticleThumbUp userArticleThumbUp = userArticleThumbUpService.selectByPrimaryKey(userArticleThumbUpKey);
            if(userArticleThumbUp == null){
                blobArticle.setThumbUpStatus("0");
            }else{
                blobArticle.setThumbUpStatus("1");
            }
            User user = userService.selectByPrimaryKey(blobArticle.getUserId());
            if(user == null){
                return CommonResult.failed("The user does not exist while select article.");
            }
            blobArticle.setNickName(user.getNickName());
            blobArticle.setProfilePhoto(user.getProfilePhoto());
        }
        return CommonResult.success(blobArticles);
    }

    @PreAuthorize("hasRole('R_EDIT_BLOG_E')")
    @RequestMapping(value = "", method = RequestMethod.POST)
    public CommonResult create(@RequestBody BlobArticleWithBLOBs blobArticle) {
        //获取当前用户id
        String currentUserName = SecurityUserUtil.getCurrentUserName();
        Integer userId = userService.getUserIdByUserName(currentUserName);
        blobArticle.setUserId(userId);
        blobArticle.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()).toString());
        //去除content中包含的html标签
        blobArticle.setCommonContent(blobArticle.getContent().replaceAll("<[.[^<]]*>",""));
        try{
            blobArticleService.insert(blobArticle);
        }catch (Exception e){
            logger.error("Blog saved failed.",e);
            return CommonResult.failed("Blog saved failed.");
        }

        //获取插入后自动生成的id
        Integer blobArticleId = blobArticle.getId();

        //根据正则表达式对博客文章中的图片地址进行提取，然后存储到picture数据库中
        Picture picture = new Picture();
        picture.setUserId(userId);
        picture.setType(0);
        picture.setArticleId(blobArticleId);
        picture.setDeleteFlag(0);
        picture.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()).toString());
        String matchUrl = "(?:https):\\/\\/[\\w\\.-]+\\/[\\w]+\\.[\\w]+";
        List<String> urlList = new ArrayList<>();
        String needMatchStr = blobArticle.getContent();
        Pattern pattern = Pattern.compile(matchUrl);
        Matcher matcher = pattern.matcher(needMatchStr);
        while (matcher.find()) {
            picture.setId(IdGenerateUtil.generateId(IdGenerateUtil.PICTURE_ID));
            picture.setSrc(matcher.group());
            try{
                int insert = pictureService.insert(picture);
            }catch (Exception e){
                logger.error("Picture saved failed.",e);
                return CommonResult.failed("Picture saved failed.");
            }
            urlList.add(matcher.group());
        }
        return CommonResult.success("Article uploaded successfully.");
    }

    @RequestMapping(value = "/selectByExample", method = RequestMethod.GET)
    public CommonResult<BlobArticleWithBLOBs> selectByExample(@RequestParam Integer id) {
        BlobArticleWithBLOBs blobArticle = blobArticleService.selectByPrimaryKey(id);
        if(blobArticle == null){
            return CommonResult.failed("The article does not exist while select article.");
        }

        User user = userService.selectByPrimaryKey(blobArticle.getUserId());
        if(user == null){
            return CommonResult.failed("The user does not exist while select article.");
        }
        blobArticle.setNickName(user.getNickName());
        blobArticle.setProfilePhoto(user.getProfilePhoto());
        blobArticle.setLastLoginTime(user.getLastLoginTime());

        //查询用户的总获赞数、评论数、粉丝数、访问数
        UserStatistics userStatistics = userStatisticsService.selectByPrimaryKey(blobArticle.getUserId());
        if(userStatistics == null){
            return CommonResult.failed("The userStatistics does not exist while select article.");
        }
        blobArticle.setSumFansNumber(userStatistics.getSumFansNumber());
        blobArticle.setSumViewTimes(userStatistics.getSumViewTimes());
        blobArticle.setSumThumbUpTimes(userStatistics.getSumThumbUpTimes());
        blobArticle.setSumCommentTimes(userStatistics.getSumCommentTimes());
        return CommonResult.success(blobArticle);
    }
}
